package com.gooluke.netty;

import com.gooluke.netty.handler.MyClientChannelInboundHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoop;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.concurrent.TimeUnit;

/**
 * @author gooluke
 * description
 * datetime 2025-05-18 3:25
 */
public class NettyClient {

    public static void main(String[] args) {
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(new NioEventLoopGroup(8));
        bootstrap.channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline()
                                .addLast(new StringEncoder())
                                .addLast(new StringDecoder())
                                .addLast(new MyClientChannelInboundHandler());
                    }
                });
        ChannelFuture channelFuture = bootstrap.connect("localhost", 9000);
        channelFuture.addListener(future -> {
            if (future.isSuccess()) {
                System.out.println("连接成功");
                EventLoop eventExecutors = channelFuture.channel().eventLoop();
                eventExecutors.scheduleAtFixedRate(() -> {
                    channelFuture.channel().writeAndFlush("【客户端发送】：" + System.currentTimeMillis());
                }, 0, 10, TimeUnit.SECONDS);
            }
        });
    }

}
